#import "CBOpenGLView.h"
#include "CRL_Main.h"
#include <OpenGL/OpenGL.h>

@implementation CBOpenGLView

- (void)awakeFromNib
{
	[super awakeFromNib];
}

- (id)initWithFrame:(NSRect)frameRect
{
    self = [super initWithFrame: frameRect];
    
    if (self != nil)
    {
        CB_SNS(RenderLib)::COpenGLHandle Config;
        CB_SNS(RenderLib)::CMain& rMain = CB_SNS(RenderLib)::CMain::CreateInstance();
        
        Config.m_Flags  		   = CB_SNS(RenderLib)::IPlatformHandle::RenderDoubleBuffered;
        Config.m_BufferWidth  	   = [self frame].size.width;
        Config.m_BufferHeight 	   = [self frame].size.height;
        Config.m_ColorBufferFormat = CB_SNS(RenderLib)::SPixelFormat::RGB_24;
        Config.m_DepthBufferFormat = CB_SNS(RenderLib)::SPixelFormat::Depth_24;
        
        rMain.Startup(Config);
        
        [self setOpenGLContext: (NSOpenGLContext*)Config.GetContext()];
    }
    
    [[NSNotificationCenter defaultCenter] 
    	addObserver: self
           selector: @selector(_surfaceNeedsUpdate:) 
               name: NSViewGlobalFrameDidChangeNotification 
             object: self];
    
    return self;
}

// -------------------------------------------------------------------------------------------

- (void)lockFocus
{
    [super lockFocus]; 
    
    if ([_openGLContext view] != self) 
    {
        [_openGLContext setView:self];
    }
    
    [_openGLContext makeCurrentContext];
}

// -------------------------------------------------------------------------------------------

- (void)setOpenGLContext:(NSOpenGLContext*)context
{
	if (_openGLContext != nil)
    {
    	if ([_openGLContext view] == self)
        {
            [_openGLContext clearDrawable];
        }
        
    	[_openGLContext release];
        _openGLContext = nil;
    }
    
	_openGLContext = [context retain];
}

// -------------------------------------------------------------------------------------------

- (NSOpenGLContext*)openGLContext
{
	return _openGLContext;
}

// -------------------------------------------------------------------------------------------

- (void) _surfaceNeedsUpdate:(NSNotification*)notification
{
    [self update];
}

// -------------------------------------------------------------------------------------------

- (void)update
{
    if ([_openGLContext view] == self)
    {
    	[_openGLContext update];
    }
}

// -------------------------------------------------------------------------------------------

- (void)drawRect:(NSRect)rect;
{
	[_openGLContext makeCurrentContext]; 
	
    glClearColor(0,0,0,1);
    glClear(GL_COLOR_BUFFER_BIT);
    glFlush();
    
    [_openGLContext flushBuffer];
}

@end
